var editIndex = undefined;
var gridId=undefined;
var clickIndex;
$(function() {
	$.extend($.fn.validatebox.defaults.rules, {
        minLength: {
            validator: function(value, param){
                return value.length >= param[0];
            },
            message: '长度不能小于{0}位'
        },
        maxLength: {
         validator: function(value,param){
         return value.length <=param[0];
         },
         message: '长度不能大于{0}位'
        }
    });
	gridId = "domino_table"
	DominoTable.createDatagrid();
})


var DominoTable={
	//创建树
	createDatagrid : function (){
		createGrid();
	}
}



//查询
function admin_domino_searchFun() {
	$('#domino_table').datagrid('load', serializeObject($('#admin_domino_searchForm')));
}

//清空条件
function admin_domino_cleanFun() {
	$('#admin_domino_searchForm').form('clear');
}


var GridUtil = {
		append:function(){append()},
		remove:function(){remove()},
		accept:function(){accept()},
		reject:function(){reject()}
}




function createGrid(){
           $("#"+gridId).datagrid({
			url: currenthost + '/domino/query.ajax',
			title: 'Domino信息',
			iconCls: 'icon-edit',
			pagination: true,
			fitColumns:true,
			pageSize: 10,
			pageList: [10, 20, 30],
			columns: [[{
				field: 'id',
				hidden: true
			},
			{
				field: 'gmtCreated',
				hidden: true
			},
			{
				field: 'name',
				title: '名称',
				width:  100,
				editor:'text'
			},
			{
				field: 'server',
				title: '服务器',
				width:  100,
				editor:{
					type:'validatebox',
					options:{
						required:true
					}
				}
			},
			{
				field: 'port',
				title: '端口',
				width:  50,
				editor:{
					type:'validatebox',
					options:{
						required:true
					}
				}
			},
			{
				field: 'dbPath',
				title: '索引库',
				width:  150,
				editor:{
					type:'validatebox',
					options:{
						required:true
					}
				}
			},
			{
				field: 'userName',
				title: '用户名',
				width:  50,
				editor:{
					type:'validatebox',
					options:{
						required:true
					}
				}
			},
			{
				field: 'password',
				title: '密码',
				width:  50,
				editor:{
					type:'validatebox',
					options:{
						required:true
					}
				}
			},
			{
				field: 'statue',
				title: '状态',
				width:  50,
				editor:{
					type:'validatebox',
					options:{
						required:true,
						validType:'maxLength[1]'
					}
				}
			},
			{
				field: 'searchCondition',
				title: '搜索条件',
				width:  350,
				editor:{
					type:'validatebox',
					options:{
						required:true
					}
				}
			}]],
			toolbar: [{
				text: '增加',
				iconCls: 'icon-add',
				handler: function() {
					GridUtil.append();
				}
			},
			'-', {
				text: '删除',
				iconCls: 'icon-remove',
				handler: function() {
					GridUtil.remove();
				}
			},
			'-', {
				text: '保存',
				iconCls: 'icon-save',
				handler: function() {
					GridUtil.accept();
				}
			},
			'-', {
				text: '取消',
				iconCls: 'icon-undo',
				handler: function() {
					GridUtil.reject();
				}
			}],
			onClickRow:onClickRow,
			onDblClickRow:onDblClickRow
		});
}



function onDblClickRow(index,rowData){
	$("#"+gridId).datagrid('uncheckAll').datagrid('unselectAll').datagrid('clearSelections');
	if (editIndex != index){
		if (endEditing()){
			$('#'+gridId).datagrid('selectRow', index)
					.datagrid('beginEdit', index);
			editIndex = index;
		} else {
			$('#'+gridId).datagrid('selectRow', editIndex);
		}
	}
}


function onClickRow(index){
	$("#"+gridId).datagrid('uncheckAll').datagrid('unselectAll').datagrid('clearSelections');
	if (editIndex != index){
		if (endEditing()){
			clickIndex=index;
			var row =$('#'+gridId).datagrid('selectRow', index);
		} else {
		    clickIndex = editIndex;
			$('#'+gridId).datagrid('selectRow', editIndex);
		}
	}
}


function endEditing(){
	if (editIndex == undefined){
		$("#"+gridId).datagrid('uncheckAll').datagrid('unselectAll').datagrid('clearSelections');
		return true
		}
	if ($('#'+gridId).datagrid('validateRow', editIndex)){
		$('#'+gridId).datagrid('endEdit', editIndex);
		editIndex = undefined;
		$("#"+gridId).datagrid('uncheckAll').datagrid('unselectAll').datagrid('clearSelections');
		return true;
	} else {
		return false;
	}
}

function append(){
	if (endEditing()){
		$('#'+gridId).datagrid('appendRow',{});
		editIndex = $('#'+gridId).datagrid('getRows').length-1;
		clickIndex = editIndex;
		$('#'+gridId).datagrid('selectRow', editIndex).datagrid('beginEdit', editIndex);
	}
}


function remove(){
	if (clickIndex == null){return}
	var rows = $("#"+gridId).datagrid('getSelections');
	if(rows[0].id==null){
		$('#'+gridId).datagrid('cancelEdit', clickIndex).datagrid('deleteRow', clickIndex);
		clickIndex=null;
	}else{
		delRow(rows[0].id,clickIndex);
	}
}


function accept(){
	if (endEditing()){
		var rows = getChanges();
		if(rows.length==0){
			jQuery.messager.show({
				msg: '没有数据改变！',
				title: '提示'
			});
			return;
		}
		var result = insertRows(rows);
	}
}


function reject(){
	$('#'+gridId).datagrid('rejectChanges');
	editIndex = undefined;
}

function getChanges(){
	var rows = $('#'+gridId).datagrid('getChanges');
	return rows;
}


function insertRows(rows){
	var insertResult;
	jQuery.ajax({
		url: currenthost + '/domino/addOrUpdate.ajax',
		data: {
			rows: JSON.stringify(rows)
		},
		dataType: 'json',
		type:'POST',
		success: function(result) {
			insertResult = result;
			if(result.success){
				$.messager.alert('保存成功',"祝贺你成功保存！");
				$('#'+gridId).datagrid('reload', "");
			}else{
				$.messager.alert('保存失败',result.msg,'error');
			}
		}
	});
	return insertResult;
}

function delRow(id,index){
	jQuery.messager.confirm('确认', '您是否要删除当前选中的项目？',function(r) {
		if(!r){
			return;
		}
		jQuery.ajax({
			url: currenthost + '/domino/delete.ajax',
			data: {
				id: id
			},
			dataType: 'json',
			type:'POST',
			success: function(result) {
				delResult = result;
				if(result.success){
					$.messager.alert('删除成功',"祝贺删除成功！");
					$('#'+gridId).datagrid('cancelEdit', clickIndex).datagrid('deleteRow', clickIndex);
					clickIndex=null;
					$('#'+gridId).datagrid('reload', "");
				}else{
					$.messager.alert('删除失败',result.msg,'error');
				}
			}
		});
	});
}




var serializeObject = function(form) {
	var o = {};
	jQuery.each(form.serializeArray(),
	function(index) {
		if (o[this['name']]) {
			o[this['name']] = o[this['name']] + "," + this['value'];
		} else {
			o[this['name']] = this['value'];
		}
	});
	return o;
};
